package org.jeecg.modules.demo.crm.util.wx;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 微信头像 转 MultipartFile 的工具
 */
public class WxAvatar2MultipartFile {

    private static final OkHttpClient client = new OkHttpClient();

    public static MultipartFile convert(String headimgUrl) throws IOException {
        // 1. 下载头像
        Response resp = client.newCall(new Request.Builder().url(headimgUrl).get().build()).execute();
        if (!resp.isSuccessful()) {
            throw new IOException("下载微信头像失败, url=" + headimgUrl);
        }
        byte[] bytes = resp.body().bytes();
        resp.close();

        // 2. 构造 MultipartFile
        String fileName = "wx_avatar_" + System.currentTimeMillis() + ".jpg";
        return new MockMultipartFile(
                "file",               // 表单字段名，随便填
                fileName,             // 文件名
                "image/jpeg",         // contentType
                bytes);
    }

    public static MultipartFile convertLocal(String filePath) throws IOException {
        // 1. 从本地路径读取文件
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("文件不存在, filePath=" + filePath);
        }

        // 2. 读取文件内容到字节数组
        FileInputStream fis = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fis.read(bytes);
        fis.close();

        // 3. 构造 MultipartFile
        String fileName = file.getName();
        return new MockMultipartFile(
                "file",               // 表单字段名，随便填
                fileName,             // 文件名
                "application/octet-stream", // contentType，根据文件类型调整
                bytes);
    }
}